package org.changs.launcher.ota;

import android.os.RecoverySystem;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.DownloadListener;
import com.androidnetworking.interfaces.DownloadProgressListener;

import org.changs.aplug.base.BasePresenter;
import org.changs.aplug.base.IView;

import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;

import javax.inject.Inject;

import timber.log.Timber;

/**
 * Created by 惠安 on 2017/12/14.
 */


public class OTAPresenter extends BasePresenter<IView> {

    @Inject
    public OTAPresenter() {
    }

    public void download() {
        Timber.d("download() called");
        AndroidNetworking.download("http://120.77.155.12:18080/ota/t3_p3-ota-20171214.zip",
                "/sdcard", "t3_p3-ota-20171214.zip")
                .build()
                .setDownloadProgressListener(new DownloadProgressListener() {
                    @Override
                    public void onProgress(long bytesDownloaded, long totalBytes) {
                        Timber.d("onProgress() called with: bytesDownloaded = [" + bytesDownloaded + "], totalBytes = [" + totalBytes + "]");
                    }
                })
                .startDownload(new DownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                        Timber.d("onDownloadComplete() called");
                    }

                    @Override
                    public void onError(ANError anError) {
                        Timber.d("onError() called with: anError = [" + anError + "]");
                    }
                });
    }

    public void verifyPackage() {
        try {
            RecoverySystem.verifyPackage(new File("/sdcard/t3_p3-ota-20171214.zip"),
                    new RecoverySystem.ProgressListener() {
                        @Override
                        public void onProgress(int progress) {
                            Timber.d("onProgress() called with: progress = [" + progress + "]");
                        }
                    }, null);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
    }

    public void installPackage() {
        try {
            RecoverySystem.installPackage(getMvpView().getContext(), new File("/sdcard/t3_p3-ota-20171214.zip"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
